package com.rongxun.http;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/5/18 14:07
 * 描述	     网络请求配置
 * <p>
 */

public class ApiProvider {
    private static final long TIMEOUT = 15;
    private final Retrofit   mRetrofit;
    private       ApiService mApiService;

    public ApiProvider(String pBaseUrl) {
        this(pBaseUrl, null);
    }

    public ApiProvider(String pBaseUrl, OkHttpClient pClient) {
        if (pClient == null) {
            pClient = createDefaultClient();
        }

        mRetrofit = new Retrofit.Builder()
                .baseUrl(pBaseUrl)
                .client(pClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    private OkHttpClient createDefaultClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor())
                .addInterceptor(Api.sloggingInterceptor)
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .build();
    }

    public ApiService getApi() {
        if (mApiService == null) {
            synchronized (ApiProvider.class) {
                if (mApiService == null) {
                    mApiService = mRetrofit.create(ApiService.class);
                }
            }
        }
        return mApiService;
    }

}
